package com.myzhouye.biz.security;/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

/**
 * @program: game01
 * @description:
 * @author: 那条蠢鱼
 * @create: 2025-11-05 17:01
 **/
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.server.WebFilter;

/**
 * WebFlux 响应式安全配置（集成 Redis Token 认证）
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityConfig {

    // 注入自定义 Token 过滤器（RedisTokenWebFilter）
    private final WebFilter redisTokenWebFilter;

    private final SecurityProperties securityProperties;

    // 构造函数注入过滤器
    // 修改构造函数，注入配置属性
    public SecurityConfig(RedisTokenWebFilter redisTokenWebFilter, SecurityProperties securityProperties) {
        this.redisTokenWebFilter = redisTokenWebFilter;
        this.securityProperties = securityProperties;
    }

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                // 1. 禁用 CSRF（API 场景无需 CSRF 保护）
                .csrf(csrf -> csrf.disable())

                // 2. 配置 URL 访问权限
                .authorizeExchange(exchanges -> exchanges
                        // 公开接口：登录/注销、视图页面、Swagger 文档
                        .pathMatchers(securityProperties.getIgnoreUrls().toArray(new String[0])).permitAll()
                        // 其他接口需认证
                        .anyExchange().authenticated()
                )

                // 3. 添加自定义 Token 过滤器（在认证阶段前执行）
                .addFilterBefore(redisTokenWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)

                // 4. 构建安全链
                .build();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        // 密码加密器，WebFlux环境同样适用
        return new BCryptPasswordEncoder();
    }

    @Bean
    public ReactiveAuthenticationManager reactiveAuthenticationManager(
            ReactiveUserDetailsService userDetailsService,
            PasswordEncoder passwordEncoder) {
        // 使用基于用户详情服务的响应式认证管理器
        UserDetailsRepositoryReactiveAuthenticationManager manager =
                new UserDetailsRepositoryReactiveAuthenticationManager(userDetailsService);
        manager.setPasswordEncoder(passwordEncoder);
        return manager;
    }
}
